import React, { PureComponent } from "react";
import { Howl } from "howler";
import QRCode from "qrcode.react";
import { HttpClient } from "../../commoe/HttpClient";
import {
  Footer,
  Header,
  Arwes,
  Image,
  Words,
  Frame,
  Table,
  Button,
  Project,
  Row,
  Col,
  Link,
} from "arwes";
import XLSX from "xlsx";
export default class personalData extends PureComponent {
  constructor(props) {
    super(props);
    this.sounds = {
      click: new Howl({
        src: ["./sound/click.mp3"],
      }),
      typing: new Howl({
        src: ["./sound/typing.mp3"],
      }),
      deploy: new Howl({
        src: ["./sound/deploy.mp3"],
      }),
    };
    this.state = {
      show: false,
      xiaoquname: "锦绣苑小区",
      xiaoqunamestr: "锦绣苑小区",
      firstList: [],
      firstList1: [],
    };
  }
  componentDidMount() {
    this.refs.getfile.addEventListener("change", readfile, false);
    const that = this;
    function readfile() {
      let file = this.files[0];
      let filename = this.files[0].name;
      let reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = (filee) => {
        const result = filee.target.result;
        const workbook = XLSX.read(result, { type: "binary" });
        let data = []; // 存储获取到的数据
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            data = data.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            );
            break; // 如果只取第一张表，就取消注释这行
          }
        }
        for (let i = 0; i < data.length; i++) {
          data[i] = { "房屋ID*": "", ...data[i] };
        }
        that.setState({
          firstList: data,
        });
      };
    }
    this.refs.getfile1.addEventListener("change", readfile1, false);
    function readfile1() {
      let file = this.files[0];
      let filename = this.files[0].name;
      let reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = (filee) => {
        const result = filee.target.result;
        const workbook = XLSX.read(result, { type: "binary" });
        let data = []; // 存储获取到的数据
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            data = data.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { range: 1 })
            );
            break; // 如果只取第一张表，就取消注释这行
          }
        }
        that.setState({
          firstList1: data.concat(that.state.firstList1),
        });
      };
    }

    this.setState({
      show: true,
    });
  }
  gohome = (url) => {
    if (this.props.location.pathname == url) {
      return;
    }
    this.sounds.click.play();
    this.sounds.deploy.play();
    this.setState({
      show: !this.state.show,
    });
    setTimeout(() => {
      this.props.history.push(url);
    }, 500);
  };
  uploadFirst = () => {
    this.refs.getfile.click();
  };
  uptrue = () => {
    const { firstList, firstList1, xiaoquname } = this.state;
    const skus = [];
    const falseskus = [];
    for (let i = 0; i < firstList.length; i++) {
      if (firstList[i]["房屋ID*"]) {
        skus.push({
          "房屋ID*": firstList[i]["房屋ID*"],
          "姓名*": firstList[i]["姓名"],
          "证件类型*":
            firstList[i]["证件类型"] == "居民身份证" ? "身份证" : "护照",
          "证件号*": firstList[i]["身份证号"],
          "政治面貌*": firstList[i]["政治面貌"],
          "国籍*": "中国",
          "民族*": firstList[i]["民族"] || "汉族",
          "与房主关系*": firstList[i]["与房主关系"],
          "是否常住本房屋*":
            firstList[i]["人口类型"] == "常住人口" ? "是" : "否",
          "是否重点关注人群*": "否",
          "手机号码*": firstList[i]["手机号"],
          "人口类型*": "户籍人口-常住人口",
          "婚姻状况*": firstList[i]["婚姻状况"] || "其他",
          籍贯: firstList[i]["籍贯"],
          曾用名: firstList[i]["曾用名"],
          人员类别: firstList[i]["人员类别"],
          健康状况: firstList[i]["健康状况"],
          兵役状况: firstList[i]["兵役状况"],
          社保状态: firstList[i]["社保状态"],
          是否社会救助对象: firstList[i]["是否社会救助对象"],
          是否科技工作者: firstList[i]["是否科技工作者"],
          学历: firstList[i]["学历"],
          专业: firstList[i]["专业"],
          毕业学校: firstList[i]["毕业学校"],
          职业类别: firstList[i]["职业类别"],
          职业: firstList[i]["职业"],
          现工作单位: firstList[i]["现工作单位"],
          参加工作时间: firstList[i]["参加工作时间"],
          退休类型: firstList[i]["退休类型"],
          退休时间: "",
          劳动保障情况: firstList[i]["劳动保障情况"],
          流动原因: firstList[i]["流动原因"],
          "停（居）留证件种类": firstList[i]["停（居）留证件种类"],
          "停（居）留证件号码": firstList[i]["停（居）留证件号码"],
          登记日期: firstList[i]["登记日期"],
          证件到期日期: firstList[i]["证件到期日期"],
          流动住所类型: firstList[i]["流动住所类型"],
          外出原因: firstList[i]["外出原因"],
          外出时间: firstList[i]["外出时间"],
          外出去向: firstList[i]["外出去向"],
          外出详址: firstList[i]["外出详址"],
          落户时间: firstList[i]["落户时间"],
          居住地址: firstList[i]["居住地址"],
          空挂原因: firstList[i]["空挂原因"],
          外文姓: firstList[i]["外文姓"],
          外文名: firstList[i]["外文名"],
          证件有效期: firstList[i]["证件有效期"],
          入境时间: firstList[i]["入境时间"],
          签证类型: firstList[i]["签证类型"],
          来华目的: firstList[i]["来华目的"],
          预计离开时间: firstList[i]["预计离开时间"],
          是否为党员: firstList[i]["是否为党员"],
          户别类型: firstList[i]["户别类型"],
          户籍详细地址: firstList[i]["户籍详细地址"],
        });
      } else {
        falseskus.push(firstList[i]);
      }
    }
    const merges = [];
    const ws = XLSX.utils.json_to_sheet(skus);
    ws["!merges"] = merges;
    // 设置每列的列宽，10代表10个字符，注意中文占2个字符x
    ws["!cols"] = [{ wch: 10 }, { wch: 30 }, { wch: 25 }];
    // 新建book
    const wb = XLSX.utils.book_new();
    // 生成xlsx文件(book,sheet数据,sheet命名)
    XLSX.utils.book_append_sheet(wb, ws, "实有人口导入模板");
    // 写文件(book,xlsx文件名称)
    try {
      XLSX.writeFile(wb, "已合并数据.xlsx");
    } catch (err) {
      console.log(err);
      message.error("导出失败");
    }
    this.setState({
      firstList: falseskus,
    });
  };
  upfalse = () => {
    const { firstList, firstList1, xiaoquname } = this.state;
    const skus = [];
    const falseskus = [];
    for (let i = 0; i < firstList.length; i++) {
      if (!firstList[i]["房屋ID*"]) {
        skus.push(firstList[i]);
      } else {
        falseskus.push(firstList[i]);
      }
    }
    const merges = [];
    const ws = XLSX.utils.json_to_sheet(skus);
    ws["!merges"] = merges;
    // 设置每列的列宽，10代表10个字符，注意中文占2个字符x
    ws["!cols"] = [{ wch: 10 }, { wch: 30 }, { wch: 25 }];
    // 新建book
    const wb = XLSX.utils.book_new();
    // 生成xlsx文件(book,sheet数据,sheet命名)
    XLSX.utils.book_append_sheet(wb, ws, "人员基本信息");
    // 写文件(book,xlsx文件名称)
    try {
      XLSX.writeFile(wb, "未合并数据.xlsx");
    } catch (err) {
      console.log(err);
      message.error("导出失败");
    }
    this.setState({
      firstList: falseskus,
    });
  };
  changedata = () => {
    const { firstList, firstList1, xiaoquname } = this.state;
    const newmap = {};
    const newList = [];
    const newList1 = [];
    for (let i = 0; i < firstList1.length; i++) {
      newmap[
        xiaoquname +
          firstList1[i]["所属建筑"] +
          firstList1[i]["所属单元"] +
          firstList1[i]["门牌号"]
      ] = firstList1[i];
    }
    for (let i = 0; i < firstList.length; i++) {
      let name =
        firstList[i]["楼名"] + firstList[i]["单元"] + firstList[i]["门牌号"];
      let option = firstList[i];
      if (newmap[name]) {
        option["房屋ID*"] = newmap[name]["编号"];
        newList.push(option);
      } else {
        newList1.push(option);
      }
    }
    this.setState({
      firstList: newList.concat(newList1),
      xiaoqunamestr: xiaoquname + "",
    });
  };
  render() {
    const { firstList, firstList1, xiaoqunamestr } = this.state;
    const firstListHead = [];
    const firstListData = [];
    for (const key in firstList[0]) {
      firstListHead.push(key);
    }
    for (let i = 0; i < firstList.length; i++) {
      let option = [];
      for (const key in firstList[i]) {
        option.push(firstList[i][key]);
      }
      firstListData.push(option);
    }
    const firstListHead1 = [];
    const firstListData1 = [];
    for (const key in firstList1[0]) {
      firstListHead1.push(key);
    }
    for (let i = 0; i < firstList1.length; i++) {
      let option = [];
      for (const key in firstList1[i]) {
        option.push(
          <div style={{ whiteSpace: "nowrap" }}>{firstList1[i][key]}</div>
        );
      }
      firstListData1.push(option);
    }
    const firstlistChildrenRender = (items) => {
      let istrue = false;
      return items.map((item, index) => {
        if (index == 0) {
          if (item) {
            istrue = true;
          }
          return (
            <div
              style={{ whiteSpace: "nowrap", color: "#00ff00" }}
              key={"firstlistrender" + index}
            >
              {item}
            </div>
          );
        } else if (index == 6) {
          if (item.indexOf(xiaoqunamestr) != -1) {
            return (
              <div
                style={{ whiteSpace: "nowrap" }}
                key={"firstlistrender" + index}
              >
                <span style={{ color: "#df9527" }}>{xiaoqunamestr}</span>
                <span style={{ color: istrue ? "#00ff00" : "#ff0000" }}>
                  {item.replace(xiaoqunamestr, "")}
                </span>
              </div>
            );
          } else {
            return (
              <div
                style={{ whiteSpace: "nowrap", color: "#999999" }}
                key={"firstlistrender" + index}
              >
                {item}
              </div>
            );
          }
        } else {
          return (
            <div
              style={{ whiteSpace: "nowrap" }}
              key={"firstlistrender" + index}
            >
              {item}
            </div>
          );
        }
      });
    };

    const firstlistrender = firstListData.map((item, index) => {
      return firstlistChildrenRender(item);
    });
    return (
      <Arwes
        timeout={1500}
        animate
        show={this.state.show}
        background="./img/background-large.jpg"
        pattern="./img/glow.png"
        style={{ height: "100%" }}
      >
        <div
          style={{ height: "100%", display: "flex", flexDirection: "column" }}
        >
          <Header animate show={this.state.show}>
            <div
              style={{
                margin: "0 auto",
                maxWidth: 800,
                padding: "20px 0",
                textAlign: "left",
                position: "relative",
              }}
            >
              <a
                style={{
                  textAlign: "left",
                  width: "50%",
                  float: "left",
                  padding: "0 10px",
                  display: "inline-block",
                }}
              >
                <Image
                  show={this.state.show}
                  onClick={() => this.gohome("/")}
                  layer={"header"}
                  animate
                  resources="./img/mine.jpeg"
                  style={{
                    width: 45,
                    height: 45,
                    margin: 0,
                    display: "inline-block",
                  }}
                ></Image>
                <Words
                  onClick={() => this.gohome("/")}
                  animate
                  show={this.state.show}
                  style={{
                    display: "inline-block",
                    fontSize: 28,
                    color: "#a1ecfb",
                    fontFamily: "Electrolize, sans-serif",
                    textShadow: "0 0 4px",
                    fontWeight: "bold",
                    textTransform: "uppercase",
                    margin: "0 0 0 10px",
                    paddingTop: 4,
                    lineHeight: 1,
                    verticalAlign: "middle",
                  }}
                >
                  GUO WÉNJUN
                </Words>
              </a>
              <div
                style={{
                  textAlign: "right",
                  width: "50%",
                  float: "right",
                  padding: "0 10px",
                  marginLeft: "auto",
                }}
              >
                <Link
                  onClick={() => this.gohome("/blog")}
                  style={{
                    fontFamily: "Electrolize,sans-serif",
                    lineHeight: "45px",
                  }}
                >
                  <i className="mdi mdi-note-outline" /> Blog
                </Link>
                <Link
                  onClick={() => this.gohome("/paper")}
                  style={{ marginLeft: 20, lineHeight: "45px" }}
                >
                  <i className="mdi mdi-box-cutter" /> Paper
                </Link>
                <Link
                  onClick={() => this.gohome("/tools")}
                  style={{ marginLeft: 20, lineHeight: "45px" }}
                >
                  <i className="mdi mdi-calculator" /> Tools
                </Link>
              </div>
              <div style={{ clear: "both" }}></div>
            </div>
          </Header>
          <div
            style={{
              flex: "1",
              padding: "20px 0",
              overflowY: "auto",
            }}
          >
            <div
              style={{
                margin: "0 auto",
                maxWidth: "80%",
                marginBottom: 0,
              }}
            >
              <input
                id="getfile"
                ref="getfile"
                type="file"
                style={{ display: "none" }}
              />
              <input
                id="getfile1"
                ref="getfile1"
                type="file"
                style={{ display: "none" }}
              />
              <div style={{ fontSize: 24 }}>
                <Link show={this.state.show}>
                  <i className="mdi mdi-chevron-double-right" />
                  <Words
                    show={this.state.show}
                    animate
                    style={{ marginLeft: 5 }}
                  >
                    网格人员数据合并工具
                  </Words>
                </Link>

                <Link style={{ float: "right" }} show={this.state.show}>
                  <i className="mdi mdi-chevron-double-left" />
                </Link>
              </div>
              <Row style={{ fontSize: 14 }}>
                <Col s={4}>
                  <Frame style={{ marginTop: 20, padding: "10px" }}>
                    <Link show={this.state.show}>
                      <i className="mdi mdi-chevron-double-right" />
                      <Words
                        show={this.state.show}
                        animate
                        style={{ marginLeft: 5 }}
                      >
                        原系统导出的人员信息
                      </Words>
                    </Link>
                    <Link show={this.state.show}>
                      <a
                        style={{ float: "right" }}
                        onClick={() => {
                          this.refs.getfile.click();
                        }}
                      >
                        上传
                      </a>
                    </Link>

                    <Link show={this.state.show}>
                      <a
                        style={{ float: "right", marginRight: 10 }}
                        onClick={() => {
                          this.setState({
                            firstList: [],
                          });
                        }}
                      >
                        清空
                      </a>
                    </Link>
                    <Table
                      style={{
                        overflowY: "auto",
                      }}
                      animate
                      headers={firstListHead}
                      dataset={firstlistrender}
                    />
                  </Frame>
                </Col>
                <Col s={4}>
                  <Frame style={{ marginTop: 20, padding: "10px" }}>
                    <Link show={this.state.show}>
                      <i className="mdi mdi-chevron-double-right" />
                      <Words
                        show={this.state.show}
                        animate
                        style={{ marginLeft: 5 }}
                      >
                        现在系统导出的网格
                      </Words>
                    </Link>
                    <Link show={this.state.show}>
                      <a
                        style={{ float: "right" }}
                        onClick={() => {
                          this.refs.getfile1.click();
                        }}
                      >
                        上传
                      </a>
                    </Link>

                    <Link show={this.state.show}>
                      <a
                        style={{ float: "right", marginRight: 10 }}
                        onClick={() => {
                          this.setState({
                            firstList1: [],
                          });
                        }}
                      >
                        清空
                      </a>
                    </Link>
                    <Table
                      animate
                      headers={firstListHead1}
                      dataset={firstListData1}
                    />
                  </Frame>
                </Col>
                <Col s={4}>
                  <Frame style={{ marginTop: 20, padding: "10px" }}>
                    <Link show={this.state.show}>
                      <i className="mdi mdi-chevron-double-right" />
                      <Words
                        show={this.state.show}
                        animate
                        style={{ marginLeft: 5 }}
                      >
                        操作栏
                      </Words>
                    </Link>
                    <div style={{ marginTop: 10 }}>
                      <Row style={{ fontSize: 14 }}>
                        <Col s={12} style={{ color: "#df9527" }}>
                          小区名称：
                          <input
                            style={{
                              backgroundColor: "rgba(100,100,100,0)",
                              borderColor: "rgba(172,249,251,0.65)",
                              color: "#df9527",
                            }}
                            value={this.state.xiaoquname}
                            onChange={(e) => {
                              this.setState({ xiaoquname: e.target.value });
                            }}
                          />
                        </Col>
                      </Row>
                    </div>
                    <Row
                      style={{
                        fontSize: 14,
                        textAlign: "center",
                        marginTop: 10,
                      }}
                    >
                      <Col s={4}>
                        <Button
                          animate
                          layer="secondary"
                          onClick={() => {
                            this.uptrue();
                          }}
                        >
                          已合数据
                        </Button>
                      </Col>
                      <Col s={4}>
                        <Button
                          animate
                          layer="secondary"
                          onClick={() => {
                            this.upfalse();
                          }}
                        >
                          未合数据
                        </Button>
                      </Col>
                      <Col s={4}>
                        <Button
                          animate
                          layer="success"
                          onClick={() => {
                            this.changedata();
                          }}
                        >
                          刷新数据
                        </Button>
                      </Col>
                    </Row>
                  </Frame>
                </Col>
              </Row>
            </div>
          </div>
          <Footer animate show={this.state.show} style={{ textAlign: "left" }}>
            <div
              style={{
                margin: "0 auto",
                maxWidth: 800,
                padding: "20px 0",
                textAlign: "left",
                position: "relative",
              }}
            >
              <Link href="https://gitee.com/mimidegongkai" target="_blank">
                <i className="mdi mdi-code-brackets" />
                <Words show={this.state.show} animate style={{ marginLeft: 5 }}>
                  Codebase
                </Words>
              </Link>

              <Link
                style={{ float: "right" }}
                href="http://beian.miit.gov.cn/"
                target="_blank"
              >
                <Words show={this.state.show} animate style={{ marginLeft: 5 }}>
                  京ICP备2021006930号
                </Words>
              </Link>
              <div style={{ clear: "both" }}></div>
            </div>
          </Footer>
        </div>
      </Arwes>
    );
  }
}
